import { useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { message } from 'antd';
import { getAdminUserInfo } from '../api/userController';
import { checkTokenCookie, clearTokenCookie } from '../util/cookieUtils';
import { useDispatch } from 'react-redux';
import { setLoginUser } from '../store/loginUser';
import { DEFAULT_USER } from '../store/loginUser';


export function UserStatusChecker() {
  const navigate = useNavigate();
    const dispatch = useDispatch();
  useEffect(() => {
    const checkUserStatus = async () => {
      if (!checkTokenCookie()) {
        try {
          const res = await getAdminUserInfo();
          if (res.code === 401) {
            message.error('登录过期，请重新登录');
            dispatch(setLoginUser(DEFAULT_USER));
            clearTokenCookie();
            navigate('/login', { replace: true });
          }
        } catch (error) {
          console.error('Failed to get user info:', error);
        }
      }
    };

    checkUserStatus();
    const intervalId = setInterval(checkUserStatus, 60000);
    return () => clearInterval(intervalId);
  }, [navigate]);

  return null;
}